package com.algorithm.utils.shorturl;

import lombok.extern.log4j.Log4j2;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 生成步长为1的短URL,起始值为0aA
 *
 * @Author _G5niusX
 * @Date 2018/4/24 20:28
 */
@Log4j2
public class ShortURLGenerator {

    private static final char[] LOW_CASE_CHARS = new char[26];
    private static final char[] UPPER_CASE_CHARS = new char[26];
    private static final char[] NUMBERS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    private static final int LOW_A_POSITION = 97;
    private static final int UPPER_A_POSITION = 65;
    private static final char[] COMPLEX_CHARS = new char[LOW_CASE_CHARS.length + UPPER_CASE_CHARS.length + NUMBERS.length];

    static {
        for (int i = LOW_A_POSITION; i < LOW_A_POSITION + LOW_CASE_CHARS.length; i++) {
            int index = Math.abs(LOW_A_POSITION - i);
            LOW_CASE_CHARS[index] = (char) i;
        }
        for (int i = UPPER_A_POSITION; i < UPPER_A_POSITION + UPPER_CASE_CHARS.length; i++) {
            int index = Math.abs(UPPER_A_POSITION - i);
            UPPER_CASE_CHARS[index] = (char) i;
        }
        System.arraycopy(LOW_CASE_CHARS, 0, COMPLEX_CHARS, 0, LOW_CASE_CHARS.length);
        System.arraycopy(UPPER_CASE_CHARS, 0, COMPLEX_CHARS, UPPER_CASE_CHARS.length, UPPER_CASE_CHARS.length);
        System.arraycopy(NUMBERS, 0, COMPLEX_CHARS, LOW_CASE_CHARS.length + UPPER_CASE_CHARS.length, NUMBERS.length);
    }


    /**
     * 根据传入的补偿,将10进制转为62进制
     *
     * @param number
     * @return
     */
    public static String decimalSystem62System(long number) {
        Long rest = number;
        Deque<Character> stack = new ArrayDeque<>();
        StringBuilder result = new StringBuilder(0);
        while (rest != 0) {
            stack.add(COMPLEX_CHARS[new Long((rest - (rest / 62) * 62)).intValue()]);
            rest = rest / 62;
        }
        for (; !stack.isEmpty(); ) {
            result.append(stack.pop());
        }
        return result.toString();
    }

    public static String generate(String url) {
        //将传入的url放入到数据库中来获得当前的+1步长,然后来生产一个短url
        int index = 0;
        return decimalSystem62System(index);
    }

    public static void main(String[] args) {

    }
}
